namespace DigitalCv.Desktop.ViewModels
{
    using Caliburn.Micro;

    using DigitalCv.Data;

    using Microsoft.Win32;

    using SaveFileDialog = Microsoft.Win32.SaveFileDialog;

    public sealed class ShellViewModel : Conductor<IScreen>
    {
        private readonly IDigitalCvRespository digitalCvRepository;

        private Cv digitalCv;

        public ShellViewModel()
        {
            this.DisplayName = "DigitalCV";
            this.digitalCvRepository = new DigitalCvRespository();
        }

        private string FilePath { get; set; }

        public Cv DigitalCv
        {
            get
            {
                return this.digitalCv;
            }

            set
            {
                this.digitalCv = value;
                this.CanSaveDigitalCv = value != null;
            }
        }

        public bool CanSaveDigitalCv { get; private set; }

        public void NewDigitalCv()
        {
            var saveFileDialog = new SaveFileDialog
                {
                    Filter = "Digital CV File (*.dcv)|*.dcv|Show All Files (*.*)|*.*",
                    FileName = "Untitled",
                    Title = "New"
                };

            if (saveFileDialog.ShowDialog() != true)
            {
                return;
            }

            this.FilePath = saveFileDialog.FileName;
            this.DigitalCv = this.digitalCvRepository.NewDigitalCv();
            this.digitalCvRepository.SaveDigitalCv(this.DigitalCv, this.FilePath);

            this.ActivateItem(new DigitalCvViewModel(this.DigitalCv));
        }        

        public void OpenDigitalCv()
        {
            var openFileDialog = new OpenFileDialog()
                {
                    Filter = "Digital CV File (*.dcv)|*.dcv|Show All Files (*.*)|*.*",
                    Title = "Open"
                };

            if (openFileDialog.ShowDialog() != true)
            {
                return;
            }

            this.FilePath = openFileDialog.FileName;
            this.DigitalCv = this.digitalCvRepository.OpenDigitalCv(this.FilePath);
            this.ActivateItem(new DigitalCvViewModel(this.DigitalCv));
        }

        public void SaveDigitalCv()
        {
            if (this.CanSaveDigitalCv)
            {
                this.digitalCvRepository.SaveDigitalCv(this.DigitalCv, this.FilePath);
            }
        }

        public void Exit()
        {
            this.TryClose();
        }
    }
}